<?php

namespace support;

use common\exception\LogicException;

/**
 * 单例工具类
 */
trait SingletonTrait
{
    // class instance container
    private static array $instance = [];

    /**
     * @return self
     */
    public static function getInstance()
    {
        $className = get_called_class();
        $classNameMd5 = md5($className);
        if (is_null(self::$instance) || !isset(self::$instance[$classNameMd5])) {
            if (!class_exists($className)) {
                throw new LogicException("class $className not exist", ErrorCode::CLASS_DOES_NOT_EXIST);
            }
            self::$instance[$classNameMd5] = new $className();
        }
        return self::$instance[$classNameMd5];
    }
}